<template>
  <div class="vehicle-info-container">
    <h2 class="title">车辆信息</h2>
    <!-- 车辆类型选择 -->
    <van-field
      v-model="formfullData.vehicleTypeName"
      label="车辆类型"
      placeholder="请选择车辆类型"
      @click="showPicker = true"
    />
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker
        :columns="vehicleColumns"
        @confirm="handleConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <!-- 车辆状态选择 -->
    <p class="field-label">车辆状态</p>
    <van-radio-group v-model="formfullData.vehicleStatus" @change="vehicleStatusChange">
      <van-radio name="01">新车（未上牌）</van-radio>
      <van-radio name="02">新车（已上牌）</van-radio>
      <van-radio name="03">续保车辆</van-radio>
    </van-radio-group>
    <!-- 行驶证照片上传 -->
    <p class="field-label">行驶证照片上传</p>
    <div class="id-card-item" @click="handleTakePhoto('back')">
        <van-icon name="photograph" v-if="!singleImageUrlReverse" size="32" color="#999" />
        <p v-if="!singleImageUrlReverse">点击拍摄或上传</p>
        <van-uploader
          v-model="singleFileListReverseList"
          :max-count="1"
          :after-read="handleSingleReadreverseCard"
          :before-delete="handleSingleDeletereverseCard"
          @delete="handleSingleDeletereverseCard"
        >
          <van-button icon="photograph" type="primary">上传照片</van-button>
        </van-uploader>
    </div>
    <!-- OCR识别结果 -->
    <p class="field-label">OCR识别结果</p>
    <!-- 号牌号码 -->
    <van-field
      v-model="formfullData.licensePlate"
      label="号牌号码"
      placeholder="自动识别"
    ></van-field>
    <!-- 车辆类型 --> 
    <van-field
      v-model="formfullData.vehicleTypeOcr"
      label="车辆类型"
      placeholder="自动识别"
    ></van-field>
    <!-- 所有人  -->
    <van-field
      v-model="formfullData.owner"
      label="所有人 "
      placeholder="所有人"
    ></van-field>
    <!-- 使用性质 -->
    <van-field
      v-model="formfullData.usageNature"
      label="使用性质"
      placeholder="使用性质"
    ></van-field>
    <!-- 品牌型号 -->
    <van-field
      v-model="formfullData.brandModel"
      label="品牌型号"
      placeholder="品牌型号"
    ></van-field>
    <!-- 车辆识别代号  -->
    <van-field
      v-model="formfullData.vin"
      label="车辆识别代号 "
      placeholder="车辆识别代号 "
    ></van-field>
    <!-- 发动机号码 -->
    <van-field
      v-model="formfullData.engineNumber"
      label="发动机号码"
      placeholder="发动机号码"
    > </van-field>
    <!-- 注册日期 -->
    <van-field
      v-model="formfullData.registrationDate"
      label="注册日期"
      placeholder="注册日期"
    ></van-field>
    <!-- 发证日期 -->
    <van-field
      v-model="formfullData.issuanceDate"
      label="发证日期"
      placeholder="发证日期"
    ></van-field>
    <div class="z">请核对识别信息，如信息有误，可以重新拍照读取</div>
      <!-- 交强险 -->
      <div v-if="formfullData.vehicleStatus == '03'">
        <p class="field-label">录入上年度交强险保单信息</p>
        <van-field
            v-model="formfullData.compulsoryInsuranceAddressName"
            label="承保地区"
            placeholder="请选择"
            readonly
            @click="showBasePicker = true"
          />
          <van-popup v-model:show="showBasePicker" position="bottom">
            <van-picker
              :columns="baseOptions"
              @confirm="handleBaseConfirm"
              @cancel="showBasePicker = false"
            />
          </van-popup>
          <van-field
              v-model="formfullData.compulsoryInsuranceCompanyName"
              label="承保公司"
              placeholder="请选择"
              readonly
              @click="showBasePickerCompany = true"
            />
          <van-popup v-model:show="showBasePickerCompany" position="bottom">
            <van-picker
              :columns="baseOptionsCompany"
              @confirm="handleBaseConfirmCompany"
              @cancel="showBasePickerCompany = false"
            />
          </van-popup>
          <van-field
              v-model="formfullData.compulsoryInsurancePolicy"
              label="保单号"
              placeholder="请输入"
            />
          <div class="id-card-item" >
              <van-icon name="photograph" v-if="!jqx" size="32" color="#999" />
              <p v-if="!jqx">上传交强险照片</p>
              <van-uploader
                v-model="jqxList"
                :max-count="1"
                :after-read="jqxImageUrl"
                :before-delete="deljqxImageUrl"
                @delete="deljqxImageUrl"
              >
                <van-button icon="photograph" type="primary">上传照片</van-button>
              </van-uploader>
          </div>
      </div>
      <!-- 商业险 -->
      <div v-if="formfullData.vehicleStatus == '03'">
        <p class="field-label">录入上年度商业险保单信息</p>
        <van-field
            v-model="formfullData.commercialInsuranceAddress"
            label="承保地区"
            placeholder="请选择"
            readonly
            @click="showBasePicker = true"
          />
          <van-popup v-model:show="showBasePicker" position="bottom">
            <van-picker
              :columns="baseOptions"
              @confirm="handleBaseConfirm"
              @cancel="showBasePicker = false"
            />
          </van-popup>
          <van-field
              v-model="formfullData.commercialInsuranceCompany"
              label="承保公司"
              placeholder="请选择"
              readonly
              @click="showBasePickerCompany = true"
            />
          <van-popup v-model:show="showBasePickerCompany" position="bottom">
            <van-picker
              :columns="baseOptionsCompany"
              @confirm="handleBaseConfirmCompany"
              @cancel="showBasePickerCompany = false"
            />
          </van-popup>
          <van-field
              v-model="formfullData.commercialInsurancePolicy"
              label="保单号"
              placeholder="请输入"
            />
          <div class="id-card-item" >
              <van-icon name="photograph" v-if="!syx" size="32" color="#999" />
              <p v-if="!syx">上传商业险照片</p>
              <van-uploader
                v-model="syxList"
                :max-count="1"
                :after-read="syxImageUrl"
                :before-delete="delsyxImageUrl"
                @delete="delsyxImageUrl"
              >
                <van-button icon="photograph" type="primary">上传照片</van-button>
              </van-uploader>
          </div>
      </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { showToast } from 'vant';
import {
	createNumericCaptchaImage, recognizeOcr, companyList, ytbUpload
} from '/@/api/auth/ytb.ts'
import { userInfoStrore } from '/@/stores/userInfoStore'

const store = userInfoStrore()
// 车辆类型数据，按分组整理
const vehicleGroups = [
  { type: 'A类', options: 
  [{ text: '货车（新能源）', value: '01'}, { text: '货车（油车）', value: '02'}, { text: '挂车', value: '03'}] },
  { type: 'B类', options: 
  [{ text: '出租车（新能源）', value: '04'}, { text: '出租车（油车）', value: '05'}, { text: '网约车（新能源）', value: '06'}, { text: '网约车（油车）', value: '07'}] },
  { type: 'C类', options: 
  [{ text: '摩托车', value: '08'}, { text: '拖拉机（含三轮车、农用车）', value: '09'}] },
  { type: 'D类', options: 
  [{ text: '私家车（新能源）', value: '10'}] },
  { type: 'E类', options: 
  [{ text: '其他车型', value: '99'}] },
];
const formfullData = ref({
  vehicleStatus: '01'
})
const formfullDataSeeion = JSON.parse(sessionStorage.getItem('formfullData'))
if(formfullDataSeeion) {
  formfullData.value = formfullDataSeeion
  if(formfullDataSeeion.vehicleBigType) {
    vehicleGroups.map(v=>{
      v.options.map(z=>{
        console.log(z.value)
        if(z.value == formfullDataSeeion.vehicleBigType) {
          formfullData.value.vehicleTypeName = z.text;
        }
      })
    })
  }
}
const plateNumber = ref('');
const showVehicleTypePicker = ref(false);
// 基础下拉选数据
const baseOptions = ref([
  { text: '河北省', value: '01' },
  { text: '非河北省', value: '02' },
  { text: '未承保', value: '03' },
]);
const showBasePicker = ref(false);
// 处理基础下拉选确认
const handleBaseConfirm = (v) => {
  // 查找选中项的文本
  formfullData.value.compulsoryInsuranceAddress = v.selectedValues
  formfullData.value.compulsoryInsuranceAddressName = v.selectedOptions[0].text
  showBasePicker.value = false;
};
const baseOptionsCompany = ref([]);
const showBasePickerCompany = ref(false);
// 处理基础下拉选确认
const handleBaseConfirmCompany = (v) => {
  // 查找选中项的文本
  formfullData.value.compulsoryInsuranceCompany = v.selectedValues
  formfullData.value.compulsoryInsuranceCompanyName = v.selectedOptions[0].text
  showBasePickerCompany.value = false;
};

const vehicleColumns = ref([]);
vehicleGroups.forEach((group) => {
  // 添加分组标题（disabled 设为 true 使其不可选）
  vehicleColumns.value.push({
    text: group.type,
    value: `group_${group.type}`,
    disabled: true,
  });
  // 循环添加该分组下的车辆类型选项
  group.options.forEach((option) => {
    vehicleColumns.value.push({
      type: group.type,
      text: option.text,
      value: option.value,
    });
  });
});
const selectedVehicleType = ref('');
const showPicker = ref(false);

// 选择确认回调
const handleConfirm = (valuez) => {
  console.log(valuez)
  // 过滤掉分组标题（分组标题 value 以 group_ 开头），只赋值车辆类型选项
  formfullData.value.vehicleType = valuez.selectedValues[0];
  formfullData.value.vehicleBigType = valuez.selectedOptions[0].type;
  formfullData.value.vehicleTypeName = valuez.selectedOptions[0].text;
  showPicker.value = false;
};
// 返回上一页
const handleGoBack = () => {
  // 实际可通过路由返回，如：history.back();
  console.log('返回上一页');
};

// 拍摄行驶证照片
const handleTakePhoto = () => {
  showToast('即将拍摄行驶证照片');
  // 实际项目中调用相机或选择图片接口
};

// OCR识别号牌号码
const handleOcr = (fieldType) => {
  showToast(`即将进行${fieldType}的OCR识别`);
  // 实际项目中调用OCR接口，识别后填充对应字段
};

const singleImageUrlReverse = ref('')
const singleFileListReverseList = ref([])
// 处理单张图片上传完成人像面
const handleSingleReadreverseCard = async(file) => {
  // 显示上传中状态
  file.status = 'uploading';
  file.message = '上传中...';
  setTimeout(() => {
    singleImageUrlReverse.value = file.content;
    file.status = 'done';
    showToast('上传成功');
  }, 1000);
  const res = await uploadImage(file.file,'vehicle_license')
  formfullData.value.licensePlate = res.data.numberPlate
  formfullData.value.vehicleTypeOcr = res.data.vehicleType
  formfullData.value.owner = res.data.owner       
  formfullData.value.usageNature = res.data.usageCharacteristics
  formfullData.value.brandModel = res.data.brandModel
  formfullData.value.vin = res.data.vin
  formfullData.value.engineNumber = res.data.engineNo
  formfullData.value.registrationDate = res.data.registrationDate
  formfullData.value.issuanceDate = res.data.issueDate
};
// 接口信息返回封装
const uploadImage = async(v,n) => {
  const formData = new FormData();
  formData.append('file', v); 
  formData.append('doc_type', n)
  const res = await recognizeOcr(formData)
  return res
};
// 处理单张图片删除
const handleSingleDeletereverseCard = () => {
  singleFileListReverseList.value = []
  singleImageUrlReverse.value = '';
  showToast('图片已删除');
};
// 续保状态
const vehicleStatusChange = (v) => {
}
// 交强险照片
const jqxList = ref([])
const jqx = ref('')
const jqxImageUrl = async(file) => {
  // 显示上传中状态
  file.status = 'uploading';
  file.message = '上传中...';
  setTimeout(() => {
    jqx.value = file.content;
    file.status = 'done';
    showToast('上传成功');
  }, 1000);
  const formData = new FormData();
  formData.append('file', file.file); 
  formData.append('doc_type', 'social_credit_code')
  const res = await ytbUpload(formData)
  if (res.code == 200) {
    formfullData.commercialInsuranceImageUrl = res.fileName
  }
};
// 处理交强险单张图片删除
const deljqxImageUrl = () => {
  jqxList.value = []
  jqx.value = '';
  showToast('图片已删除');
};
// 商业险照片
const syxList = ref([])
const syx = ref('')
const syxImageUrl = async(file) => {
  // 显示上传中状态
  file.status = 'uploading';
  file.message = '上传中...';
  setTimeout(() => {
    syx.value = file.content;
    file.status = 'done';
    showToast('上传成功');
  }, 1000);
  const formData = new FormData();
  formData.append('file', file.file); 
  formData.append('doc_type', 'social_credit_code')
  const res = await ytbUpload(formData)
  if (res.code == 200) {
    formfullData.commercialInsuranceImageUrl = res.fileName
  }
};
// 处理单张图片删除
const delsyxImageUrl = () => {
  usccImageUrlList.value = []
  syx.value = '';
  showToast('图片已删除');
};
onMounted(async()=>{
  const res = await companyList()
  res.data.map(v=>{
    baseOptionsCompany.value.push({
      text:v.companyName,
      value: v.companyCode
    })
  })
})
watch(()=>store.storeNum,(newValue,oldValue)=>{
  store.getFormfullData({...formfullData.value,...store.storeFormfullData})
})
</script>

<style lang="less" scoped>

.vehicle-info-container {
  width: 100%;
  padding: 16px;
  margin-top: 20px;
  background: #fff;
  border-radius: 10px;
  .van-field {
    padding-left: 0;
    padding-bottom: 0;
  }
  .field-select {
    width: 100%;
    height: 70px;
  }
  .van-radio-group {
    display: flex;
    flex-flow: wrap;
    justify-content: space-between; 
  }
  .van-radio {
    width: 47%;
    margin-top: 13px;
    padding: 10px 7px;
    border: 1px solid;
    border-radius: 3px;
  }
  .id-card-item {
    width: 48%;
    padding: 16px;
    margin-top: 10px;
    border-radius: 8px;
    text-align: center;
    border: 1px dashed #ddd;
    p {
      font-size: 13px;
    }
  }
  .z {
    font-size: 13px;
    text-align: left;
    margin-top: 10px;
    color: rgb(252, 118, 118);
  }
}
.title {
  font-size: 18px;
  text-align: left;
  font-weight: bold;
  margin-bottom: 16px;
}
.field-label {
  font-size: 14px;
  color: #666;
  text-align: left;
  margin-top: 10px;
  font-weight: bold;
}
.id-card-box {
  margin: 16px 0;
}
.photo-upload {
  border: 1px dashed #ddd;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
}
.tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}
.ocr-btn {
  color: #1989fa;
  cursor: pointer;
}
</style>